﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using NewLife.Caching;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq.Dynamic.Core;

using Admin.NET.Core;


namespace Admin.NET.Application;
//sywarehousenew
/// <summary>
/// 仓库服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]

public class sywarehousenewService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<sywarehousenew> _sywarehousenewRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;





    public sywarehousenewService(SqlSugarRepository<sywarehousenew> sywarehousenewRep, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService)
    {
        _sywarehousenewRep = sywarehousenewRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
  
    }

    /// <summary>
    /// 测试 Redis 连接状态
    /// </summary>
    [DisplayName("测试Redis连接")]
    [ApiDescriptionSettings(Name = "TestRedis"), HttpPost]
  
    public  string TestRedisConnection()
    {


            // 检查注入的 Redis 实例是否可用


                return "Redis 连接未就绪";
            

            // 获取数据库并执行简单操作
        
     

            
     
       
    }


    /// <summary>
    /// 分页查询仓库 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询仓库")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<sywarehousenewOutput>> Page(PagesywarehousenewInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _sywarehousenewRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.warehousecode.Contains(input.Keyword) || u.warehousename.Contains(input.Keyword) || u.waretype.Contains(input.Keyword) || u.managers.Contains(input.Keyword) || u.warehouseaddress.Contains(input.Keyword) || u.warehousedescription.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.warehousecode), u => u.warehousecode.Contains(input.warehousecode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.warehousename), u => u.warehousename.Contains(input.warehousename.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.waretype), u => u.waretype.Contains(input.waretype.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.managers), u => u.managers.Contains(input.managers.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.warehouseaddress), u => u.warehouseaddress.Contains(input.warehouseaddress.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.warehousedescription), u => u.warehousedescription.Contains(input.warehousedescription.Trim()))
            .Select<sywarehousenewOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取仓库详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取仓库详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<sywarehousenew> Detail([FromQuery] QueryByIdsywarehousenewInput input)
    {
        return await _sywarehousenewRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加仓库 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加仓库")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddsywarehousenewInput input)
    {

        // 生成仓库代码的C#实现
        string GenerateWarehouseCode()
        {
            // 获取13位毫秒级时间戳
            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
            // 生成5位随机数（00000-99999）
            var random = new Random();
            var randomSeq = random.Next(0, 100000).ToString("D5");
            return $"CK_ZAQ_{timestamp}_{randomSeq}";
        }

        input.warehousecode = GenerateWarehouseCode();
        var entity = input.Adapt<sywarehousenew>();
        return await _sywarehousenewRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新仓库 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新仓库")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatesywarehousenewInput input)
    {
        var entity = input.Adapt<sywarehousenew>();
        await _sywarehousenewRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除仓库 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除仓库")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletesywarehousenewInput input)
    {
        var entity = await _sywarehousenewRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _sywarehousenewRep.FakeDeleteAsync(entity);   //假删除
        //await _sywarehousenewRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除仓库 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除仓库")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletesywarehousenewInput> input)
    {
        var exp = Expressionable.Create<sywarehousenew>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _sywarehousenewRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _sywarehousenewRep.FakeDeleteAsync(list);   //假删除
        //return await _sywarehousenewRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出仓库记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出仓库记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagesywarehousenewInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportsywarehousenewOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        var waretypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "warehouse_type_table" }).Result.ToDictionary(x => x.Value, x => x.Label);
        list.ForEach(e => {
            e.waretypeDictLabel = waretypeDictMap.GetValueOrDefault(e.waretype ?? "", e.waretype);
        });
        return ExcelHelper.ExportTemplate(list, "仓库导出记录");
    }
    
    /// <summary>
    /// 下载仓库数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载仓库数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportsywarehousenewOutput>(), "仓库导入模板");
    }
    
    /// <summary>
    /// 导入仓库记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入仓库记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var waretypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "warehouse_type_table" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportsywarehousenewInput, sywarehousenew>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 映射字典值
                    foreach(var item in pageItems) {
                        if (string.IsNullOrWhiteSpace(item.waretypeDictLabel)) continue;
                        item.waretype = waretypeDictMap.GetValueOrDefault(item.waretypeDictLabel);
                        if (item.waretype == null) item.Error = "类型字典映射失败";
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<sywarehousenew>>();
                    
                    var storageable = _sywarehousenewRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.warehousecode?.Length > 100, "仓库编码长度不能超过100个字符")
                        .SplitError(it => it.Item.warehousename?.Length > 100, "仓库名称长度不能超过100个字符")
                        .SplitError(it => it.Item.waretype?.Length > 32, "类型长度不能超过32个字符")
                        .SplitError(it => it.Item.managers?.Length > 50, "仓管员长度不能超过50个字符")
                        .SplitError(it => it.Item.warehouseaddress?.Length > 500, "地址长度不能超过500个字符")
                        .SplitError(it => it.Item.warehousedescription?.Length > 500, "描述长度不能超过500个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
